package com.example.leixin.helloworld.service;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.leixin.helloworld.R;

public class ServiceActivity extends AppCompatActivity implements View.OnClickListener {

    public static final int UPDATE_TEXT = 1;
    private TextView textView;
    private MyService.DownloadBinder downloadBinder;

    ProgressDialog progressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);

        Button button_change_text = (Button) findViewById(R.id.button_change_text);
        button_change_text.setOnClickListener(this);
        Button button_change_text_with_handler = (Button) findViewById(R.id.button_change_text_with_handler);
        button_change_text_with_handler.setOnClickListener(this);
        Button button_change_text_run_on_ui_thread = (Button) findViewById(R.id.button_change_text_run_on_ui_thread);
        button_change_text_run_on_ui_thread.setOnClickListener(this);
        Button button_async_task = (Button) findViewById(R.id.button_async_task);
        button_async_task.setOnClickListener(this);
        textView = (TextView) findViewById(R.id.text);
        progressDialog = new ProgressDialog(this);

        Button button_start_service = (Button) findViewById(R.id.button_start_service);
        button_start_service.setOnClickListener(this);
        Button button_stop_service = (Button) findViewById(R.id.button_stop_service);
        button_stop_service.setOnClickListener(this);

        Button button_bind_service = (Button) findViewById(R.id.button_bind_service);
        button_bind_service.setOnClickListener(this);
        Button button_unbind_service = (Button) findViewById(R.id.button_unbind_service);
        button_unbind_service.setOnClickListener(this);

        Button button_start_intent_service = (Button) findViewById(R.id.button_start_intent_service);
        button_start_intent_service.setOnClickListener(this);
        Button button_download = (Button) findViewById(R.id.button_download);
        button_download.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_change_text:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText("Nice to meet you");
                    }
                }).start();
                break;
            case R.id.button_change_text_with_handler:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = UPDATE_TEXT;
                        handler.sendMessage(message);
                    }
                }).start();
                break;
            case R.id.button_change_text_run_on_ui_thread:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText("run on ui thread");
                    }
                });
                break;
            case R.id.button_async_task:
                new DownloadTask().execute();
                break;
            case R.id.button_start_service:
                Intent startIntent = new Intent(this, MyService.class);
                startService(startIntent);
                break;
            case R.id.button_stop_service:
                Intent stopIntent = new Intent(this, MyService.class);
                stopService(stopIntent);// 如服务在绑定状态，此时stopService调用不生效
                // 服务销毁的原则是其上没有一个绑定者，并且处于停止状态，这样才会调用onDestory。也就是说有多少个绑定者，就必须分别解除绑定；但是启动多次，只需要一个停止就ok了
                break;
            case R.id.button_bind_service:
                Intent bindIntent = new Intent(this, MyService.class);
                //BIND_AUTO_CREATE 自动创建和绑定服务，即onCreate onBind方法，但不会启动服务startCommand
                bindService(bindIntent, connection, BIND_AUTO_CREATE);
                // 只点击button_bind_service,再按back键回到前一个页面时，会自动触发服务的unbind onDestroy，因connection已被销毁
                break;
            case R.id.button_unbind_service:
                unbindService(connection);// 会调用服务的onDestory方法,清除掉前台通知
                break;
            case R.id.button_start_intent_service:
                Toast.makeText(this, "Main Thread id is " + Thread.currentThread().getId(), Toast.LENGTH_SHORT).show();
                Intent intenSevice = new Intent(this, MyIntentService.class);
                startService(intenSevice);
                break;
            case R.id.button_download:
                Intent intent12 = new Intent(this, DownloadActivity.class);
                startActivity(intent12);
            default:
                break;
        }
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            downloadBinder = (MyService.DownloadBinder) iBinder;
            downloadBinder.startDownload();
            downloadBinder.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_TEXT:
                    textView.setText("Nice to meet you");
                    break;
                default:
                    break;
            }
        }
    };

    class DownloadTask extends AsyncTask<Void, Integer, Boolean> {

        @Override
        protected void onPreExecute() {
            progressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            progressDialog.setMessage("Downloaded " + values[0] + "%");
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            progressDialog.dismiss();
            if (aBoolean) {
                Toast.makeText(ServiceActivity.this, "Download successed", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ServiceActivity.this, "Download failed", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            int downloadPercent = 0;
            try {
                while (true) {
                    Thread.sleep(500);
                    downloadPercent += 10;
                    publishProgress(downloadPercent);
                    if (downloadPercent >= 100) {
                        break;
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                return false;
            }

            return true;
        }
    }


}
